import * as L from "leaflet";
import { getMap, leafletInit } from "./init";
import {
  addWmsLayer,
  addimageOverlay,
  addTileLayer,
  addvideoOverlay,
} from "./addLayer";

export { leafletInit };

export interface MapAPI {
  map: L.Map;
  L: typeof L;
  addWmsLayer: typeof addWmsLayer;
  addimageOverlay: typeof addimageOverlay;
  addTileLayer: typeof addTileLayer;
  addvideoOverlay: typeof addvideoOverlay;
}
// 最大尝试次数
const MAXIMUM_ATTEMPTS = 25;

/**
 * @description: 创建地图 API
 * @returns {Promise<MapAPI>}
 */
export const leafletMapAPI = (): Promise<MapAPI> =>
  new Promise<MapAPI>((resolve, reject) => {
    let counter = 0;
    let interval: number | undefined | NodeJS.Timeout;
    const checked = () => {
      const mapInstance = getMap();
      if (counter > MAXIMUM_ATTEMPTS) {
        if (typeof interval === "number") {
          clearInterval(interval);
        }
        reject(new Error("地图实例未初始化"));
      } else if (mapInstance instanceof L.Map) {
        const apis = {
          map: mapInstance,
          L,
          addWmsLayer,
          addimageOverlay,
          addTileLayer,
          addvideoOverlay,
        };
        if (typeof interval === "number") {
          clearInterval(interval);
        }
        resolve(apis);
      } else {
        console.log(`尝试初始化地图地${counter}次`);
        counter += 1;
      }
    };
    checked();
    if (counter > 0) {
      interval = setInterval(() => checked(), 250);
    }
  });
